﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AzureProvider.ssdsClient;

namespace AzureProvider.SoupMethods
{
    public class PostTag
    {
        public string Id;
        public Guid  PostId;
        public string Tag;
    }

    public class PostTagMethods : PostRelatedMethods
    {

        protected override string containerId
        {
            get { return "Posts"; }
        }

        protected override string kind
        {
            get { return "PostTag"; }
        }

        public PostTag[] CreatePostTag(string PostID, string[] Tags)
        {
            List<PostTag> pt = new List<PostTag>();
            foreach (string str in Tags)
            {
                pt.Add(new PostTag
                {
                    Id = GetId(PostID,str),
                    PostId = new Guid(PostID),
                    Tag = str 
                });
            }
            return pt.ToArray();
        }

        protected override Entity CreateEntity(object Object)
        {
            PostTag myobj = (PostTag)Object;

            var entity = new Entity()
            {
                Id = myobj.Id ,
                Kind = kind
            };

            entity.Properties = new Dictionary<string, object>();
            entity.Properties.Add("Tag", myobj.Tag );
            entity.Properties.Add("PostId", myobj.PostId.ToString());

            return entity;
        }

        private string GetId(string PostId, string Tag)
        {
            string errMessage;
            PostTag myobj =
                GetPostTags(PostId, out errMessage).SingleOrDefault(p => p.Tag == Tag);
            if (myobj != null)
                return myobj.Id;
            else
                return Guid.NewGuid().ToString();

        }
        public override object CreateObject(Entity Entity)
        {
            PostTag myObj = new PostTag();
            myObj.Tag = (string)Entity.Properties.Single(tt => tt.Key == "Tag").Value;
            myObj.PostId = new Guid((string)Entity.Properties.Single(tt => tt.Key == "PostId").Value);

            return myObj;
        }        

        public IEnumerable<PostTag> GetPostTags(string PostId, out string errMessage)
        {
            string qry =null  ;
            if (PostId!=null)
                qry = string.Format(" from e in entities where e.Kind == \"{0}\" && e[\"PostId\"] == \"{1}\"  select e", kind, PostId);
            return base.GetObjects(qry, out errMessage).Cast<PostTag>();
        }


    }
}
